package lab4p2;

/**
 * <p>Title: ViewModelList for Lab #4 Part 2</p>
 * <p>Description: CSIS 343 Lab on Model-View-Controller</p>
 *
 */


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class ViewModelList extends JFrame {

	private static final long serialVersionUID = 1L;
	private static final String INPUT_FILE = "src/lab4p2/stars";

	private JList<Star> listView;
	private JScrollPane scrollPane;
	private JButton controller;
	
	public ViewModelList( final ListModel<Star> input_list){
		setBounds( 100, 100, 400, 300 );
		
		setLayout( null );
		
		/*
		 * Set up a JList object to display a list 
		 */
		listView = new JList<Star>( input_list );
		listView.addListSelectionListener( new ListSelectionListener(){
			/*
			 * This method will be executed each time things are selected in the JList
			 * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
			 */
			public void valueChanged(ListSelectionEvent e){
				System.out.println("Something changed in the JList");
				List<Star> selected = listView.getSelectedValuesList();
				for (Star s : selected) {
					System.out.println( s );
				}
			}
		});
		scrollPane = new JScrollPane( listView );
		scrollPane.setBounds(50, 10, 300, 200);
		add( scrollPane );

		/*
		 * The button is the controller in the Model-View-Controller paradigm. 
		 */
		controller = new JButton("Sort");
		controller.addActionListener( new ActionListener(){
			/*
			 * This method is executed each time the button is clicked.
			 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
			 */
			public void actionPerformed(ActionEvent e) {
				if (controller.getText().equals("Sort")){
					((MyListModel) input_list).sort();
					controller.setText("Unsort");
				} else {
					((MyListModel) input_list).unsort();
					controller.setText("Sort");
				}	
			}
		});
		controller.setBounds(100, 220, 100, 50);
		add(controller);
		
		setVisible( true );
		setDefaultCloseOperation( EXIT_ON_CLOSE );
	}
	
	
	/**
	 * main
	 * @param args
	 */
	public static void main(String[] args) {
		/*
		 * Set up the list model
		 */
		AbstractListModel<Star> list = new MyListModel( INPUT_FILE );

		/*
		 * Now open the window and display the list.
		 */
		new ViewModelList( list );
	}

}